package com.instpower.things.handlers;

import com.instpower.things.config.CmdEnum;
import com.instpower.things.config.Configs;
import com.instpower.things.entity.CabinetCmdLog;
import com.instpower.things.instpower.Connection;
import com.instpower.things.instpower.Handler;
import com.instpower.things.transport.DataBuffer;
import com.instpower.things.transport.Request;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @ClassName Handler0084Action
 * @Author: hellmash@gmail.com
 * @Date: 2020/6/14
 * @Version: 1.0.0
 * @Description: 设置服务器IP和端口
 */
@Component(value = "CMD0084")
public class Handler0084Action extends Handler<Request> {

    @Override
    public short getId() {
        return Configs.HOST_CMD;
    }

    @Override
    public void execute(Connection connection, Request request) throws UnsupportedEncodingException {
        String sn = request.getHeader().getAddr();
        logger.info("[{}]:Exec - CMD0084 - BEGIN",sn);
        DataBuffer buffer = request.getData().encode();
        byte[] ips = buffer.readBytes(4);
        int port = buffer.readShort();

        //release after read
        buffer.release();

        StringBuilder stb = new StringBuilder();
        for(byte ip : ips){
            stb.append(Byte.toUnsignedInt(ip)).append(".");
        }
        stb.deleteCharAt(stb.length()-1);
        logger.debug("读取到新设置的IP:{}",stb.toString());
        logger.debug("读取到新设置的端口:{}",port);
        CabinetCmdLog cmdLog = new CabinetCmdLog();
        cmdLog.setCabinetSn(request.getHeader().getAddr());
        cmdLog.setCabinetCmd(CmdEnum.SETTINGHOST);
        cmdLog.setCmdCode(String.format("0x%02x", Configs.HOST_CMD));
        cmdLog.setCabinetLog("机柜设置远程服务器成功，新服务器IP:"+ stb.toString() +",Port:"+ port +".");
        instService.logCabinetCmd(cmdLog);
        logger.info("[{}]:Exec - CMD0084 - END",sn);
    }
}
